<?php
// +----------------------------------------------------------------------
// | 消息中间件
// +----------------------------------------------------------------------
// | 处理发送消息
// +----------------------------------------------------------------------
// | 错误编码头 201xxx
// +----------------------------------------------------------------------
namespace support\middleware;


use Webman\Http\Response;
use support\Request;

class RequestCheck
{
    /**
     * @param Request $request
     * @param callable $next
     * @return Response
     * @throws \exception
     */
    public function process(Request $request, callable $next): Response
    {
        // 从header头获取token
        $XUserInfoBase64 = $request->header('x-userinfo');

        if (empty($XUserInfoBase64)) {
            throw_strack_exception("Wrong header param.", -209421);
        }

        $XUserInfoBase = json_decode(base64_decode($XUserInfoBase64), true);

        if (!empty($XUserInfoBase) && !empty($XUserInfoBase['id']) && !empty($XUserInfoBase['tenant_id'])) {
            $request->setCurrentUserId($XUserInfoBase['id']);
            $request->setTenantId($XUserInfoBase['tenant_id']);
            $request->setXUserInfo($XUserInfoBase64);
        } else {
            // 错误的header头参数
            throw_strack_exception("Wrong user info param.", -209422);
        }

        return $next($request);
    }
}
